#include "numberkeyboarddialog.h"
#include "ui_numberkeyboarddialog.h"
#include <QPainter>
#include <QPainterPath>
#include <QSignalMapper>

NumberKeyboardDialog::NumberKeyboardDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::NumberKeyboardDialog)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_DeleteOnClose);

    QList<QPushButton*> btnlist;
    btnlist.append(ui->btn_0);
    btnlist.append(ui->btn_1);
    btnlist.append(ui->btn_2);
    btnlist.append(ui->btn_3);
    btnlist.append(ui->btn_4);
    btnlist.append(ui->btn_5);
    btnlist.append(ui->btn_6);
    btnlist.append(ui->btn_7);
    btnlist.append(ui->btn_8);
    btnlist.append(ui->btn_9);
    QSignalMapper *sm = new QSignalMapper(this);
    for(int i=0; i<btnlist.size(); ++i)
    {
        connect(btnlist.at(i), SIGNAL(clicked()), sm, SLOT(map()));
        sm->setMapping(btnlist.at(i), QString().setNum(i));
    }
    connect(sm, SIGNAL(mapped(QString)), this, SLOT(slotNumber(QString)));
    connect(this, SIGNAL(finished(int)), this, SLOT(deleteLater()));
}

NumberKeyboardDialog::~NumberKeyboardDialog()
{
    delete ui;
}

void NumberKeyboardDialog::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    QPainterPath path1, path2;
    p.setPen(QPen(QColor(164, 187, 210)));
    p.setBrush(QBrush(QColor(164, 187, 210)));
    path1.moveTo(0, 0);
    path1.lineTo(width(), 0);
    path1.lineTo(width()-4, 4);
    path1.lineTo(4, 4);
    path1.lineTo(4, height()-4);
    path1.lineTo(0, height());
    path1.lineTo(0, 0);
    p.drawPath(path1);
    path2.moveTo(width(), 0);
    path2.lineTo(width(), height());
    path2.lineTo(0, height());
    path2.lineTo(4, height()-4);
    path2.lineTo(width()-4, height()-4);
    path2.lineTo(width()-4, 4);
    path2.lineTo(width(), 0);
    p.setBrush(QBrush(QColor(55, 83, 111)));
    p.setPen(QPen(QColor(55, 83, 111)));
    p.drawPath(path2);
    p.setPen(QPen(QColor(128, 160, 192)));
    p.setBrush(QBrush(QColor(128, 160, 192)));
    p.drawRect(QRect(4, 4, width()-9, height()-9));
}

void NumberKeyboardDialog::slotNumber(QString str)
{
    if(ui->lineEdit->text().length() < ui->lineEdit->maxLength())
        ui->lineEdit->setText(ui->lineEdit->text() + str);
}

void NumberKeyboardDialog::on_btn_backspace_clicked()
{
    ui->lineEdit->setText(ui->lineEdit->text().left(ui->lineEdit->text().length() - 1));
}

void NumberKeyboardDialog::on_btnConfirm_clicked()
{
    emit signalSetNumber(ui->lineEdit->text());
    close();
}

void NumberKeyboardDialog::on_btnCancel_clicked()
{
    emit signalCancel();
    close();
}

QLineEdit* NumberKeyboardDialog::getLineEdit()
{
    return ui->lineEdit;
}

void NumberKeyboardDialog::setEchoMode(bool xPassword)
{
    if(xPassword)
        ui->lineEdit->setEchoMode(QLineEdit::Password);
}
